from flask import Flask, render_template, request, redirect, url_for, flash
import os
from flask_sqlalchemy import SQLAlchemy
import mysql.connector
import _random

app = Flask(__name__)

# 模拟的用户数据
users = {
    'teacher': [],
    'student': [],
    'parent': []
}


@app.route('/', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        if 'login' in request.form:
            user_type = request.form['user_type']
            username = request.form['username']
            password = request.form['password']

            for user in users[user_type]:
                if user['username'] == username and user['password'] == password:
                    return redirect(url_for(f'{user_type}_dashboard'))
            return render_template('login_failed.html')
        elif 'register' in request.form:
            return redirect(url_for('register'))
        elif 'forgot_password' in request.form:
            return redirect(url_for('forgot_password'))

    return render_template('login.html')


@app.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'POST':
        user_type = request.form['user_type']
        username = request.form['username']
        password = request.form['password']

        for user_type_key in users:
            for user in users[user_type_key]:
                if user['username'] == username:
                    return "用户名已存在，请选择其他用户名。"

        users[user_type].append({'username': username, 'password': password})
        return redirect(url_for('register_success'))

    return render_template('register.html')


@app.route('/register_success')
def register_success():
    return render_template('register_success.html')


@app.route('/forgot_password', methods=['GET', 'POST'])
def forgot_password():
    if request.method == 'POST':
        username = request.form['username']
        new_password = request.form['new_password']

        for user_type in users:
            for user in users[user_type]:
                if user['username'] == username:
                    user['password'] = new_password
                    return redirect(url_for('password_reset_success'))

        return "用户名不存在。"

    return render_template('forgot_password.html')


@app.route('/password_reset_success')
def password_reset_success():
    return render_template('password_reset_success.html')


@app.route('/student_dashboard')
def student_dashboard():
    return render_template('student_dashboard.html')


@app.route('/teacher_dashboard')
def teacher_dashboard():
    return render_template('teacher_dashboard.html')


@app.route('/parent_dashboard')
def parent_dashboard():
    return render_template('parent_dashboard.html')


app.config['UPLOAD_FOLDER'] = 'uploads/'
app.secret_key = 'your_secret_key'


@app.route('/create_exam', methods=['GET', 'POST'])
def create_exam():
    if request.method == 'POST':
     pass

    return render_template('create_exam.html')


def get_db_connection():
    conn = mysql.connector.connect(
        host='152.136.49.229',
        user='yuyu',
        password='123456',
        database='yuyude',
        charset='utf8mb4'
    )
    return conn


@app.route('/questions')
def question_list():
    conn = get_db_connection()
    cursor = conn.cursor(dictionary=True)

    cursor.execute('SELECT * FROM questions')
    questions = cursor.fetchall()

    # 调试输出，查看 questions 内容
    print(f"Questions retrieved: {questions}")

    cursor.close()
    conn.close()

    return render_template('question_list.html', questions=questions)


@app.route('/questions/edit/<int:question_id>', methods=['GET', 'POST'])
def edit_question(question_id):
    conn = get_db_connection()
    cursor = conn.cursor(dictionary=True)

    # 查询指定ID的题目
    cursor.execute('SELECT * FROM questions WHERE id = %s', (question_id,))
    question = cursor.fetchone()

    if request.method == 'POST':
        # 获取表单数据并更新题目
        sql = '''
        UPDATE questions
        SET question_text = %s, option_a = %s, option_b = %s, option_c = %s, option_d = %s, correct_answer = %s
        WHERE id = %s
        '''
        cursor.execute(sql, (
            request.form['question_text'],
            request.form['option_a'],
            request.form['option_b'],
            request.form['option_c'],
            request.form['option_d'],
            request.form['correct_answer'],
            question_id
        ))
        conn.commit()

        cursor.close()
        conn.close()

        return redirect(url_for('question_list'))

    cursor.close()
    conn.close()

    return render_template('edit_question.html', question=question)


# @app.route('/generate_exam', methods=['GET', 'POST'])
# def generate_exam():
#     conn = get_db_connection()
#     cursor = conn.cursor(dictionary=True)
#
#     if request.method == 'POST':
#         title = request.form['title']
#         description = request.form['description']
#         question_count = int(request.form['question_count'])
#         randomize = request.form.get('randomize') == 'on'
#
#         # 创建试卷
#         cursor.execute('INSERT INTO papers (title, description) VALUES (%s, %s)', (title, description))
#         exam_id = cursor.lastrowid
#
#         # 获取题目
#         if randomize:
#             cursor.execute('SELECT id FROM questions ORDER BY RAND() LIMIT %s', (question_count,))
#         else:
#             selected_questions = request.form.getlist('question_ids')
#             cursor.execute('SELECT id FROM questions WHERE id IN (%s)' % ','.join(selected_questions))
#
#         questions = cursor.fetchall()
#
#         # 关联试卷与题目
#         for question in questions:
#             cursor.execute('INSERT INTO exam_questions (exam_id, question_id) VALUES (%s, %s)',
#                            (exam_id, question['id']))
#
#         conn.commit()
#         cursor.close()
#         conn.close()
#
#         return redirect(url_for('exam_list'))
#
#     cursor.execute('SELECT * FROM questions')
#     questions = cursor.fetchall()
#
#     cursor.close()
#     conn.close()
#
#     return render_template('generate_exam.html', questions=questions)

@app.route('/generate_exam', methods=['GET', 'POST'])
def generate_exam():
    conn = get_db_connection()
    cursor = conn.cursor(dictionary=True)

    if request.method == 'POST':
        # 选择题库处理
        xuanze_count = int(request.form['xuanze_count'])
        xuanze_randomize = 'xuanze_randomize' in request.form
        xuanze_selected_ids = request.form.getlist('xuanze_question_ids')

        tiankong_count = int(request.form['tiankong_count'])
        tiankong_randomize = 'tiankong_randomize' in request.form
        tiankong_selected_ids = request.form.getlist('tiankong_question_ids')

        zhuguan_count = int(request.form['zhuguan_count'])
        zhuguan_randomize = 'zhuguan_randomize' in request.form
        zhuguan_selected_ids = request.form.getlist('zhuguan_question_ids')

        # 创建试卷
        title = "My New Exam"
        description = "This is a dynamically generated exam."
        cursor.execute('INSERT INTO papers (title, description) VALUES (%s, %s)', (title, description))
        paper_id = cursor.lastrowid

        # 处理选择题库
        if xuanze_randomize:
            cursor.execute(f'SELECT * FROM questionsxuanze ORDER BY RAND() LIMIT %s', (xuanze_count,))
        else:
            if xuanze_selected_ids:
                cursor.execute(f'SELECT * FROM questionsxuanze WHERE id IN ({",".join(xuanze_selected_ids)})')
        xuanze_questions = cursor.fetchall()

        # 处理填空题库
        if tiankong_randomize:
            cursor.execute(f'SELECT * FROM questionstiankong ORDER BY RAND() LIMIT %s', (tiankong_count,))
        else:
            if tiankong_selected_ids:
                cursor.execute(f'SELECT * FROM questionstiankong WHERE id IN ({",".join(tiankong_selected_ids)})')
        tiankong_questions = cursor.fetchall()

        # 处理主观题库
        if zhuguan_randomize:
            cursor.execute(f'SELECT * FROM questionszhuguan ORDER BY RAND() LIMIT %s', (zhuguan_count,))
        else:
            if zhuguan_selected_ids:
                cursor.execute(f'SELECT * FROM questionszhuguan WHERE id IN ({",".join(zhuguan_selected_ids)})')
        zhuguan_questions = cursor.fetchall()

        # 保存所有题目到试卷
        all_questions = xuanze_questions + tiankong_questions + zhuguan_questions

        for question in all_questions:
            cursor.execute('''
                INSERT INTO examquestions (paper_id, question_text, option_a, option_b, option_c, option_d, correct_answer, question_type)
                VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
            ''', (
                paper_id,
                question['question_text'],
                question.get('option_a'),
                question.get('option_b'),
                question.get('option_c'),
                question.get('option_d'),
                #question['correct_answer'],
                question.get('correct_answer'),
                question['question_type']  # 添加 question_type 列
               # question.get('question_type')
            ))

        conn.commit()
        cursor.close()
        conn.close()

        return redirect(url_for('exam_list', paper_id=paper_id))

    # 如果是 GET 请求，显示所有可选题目
    cursor.execute('SELECT * FROM questionsxuanze')
    xuanze_questions = cursor.fetchall()

    cursor.execute('SELECT * FROM questionstiankong')
    tiankong_questions = cursor.fetchall()

    cursor.execute('SELECT * FROM questionszhuguan')
    zhuguan_questions = cursor.fetchall()

    cursor.close()
    conn.close()

    return render_template('generate_exam.html',
                           xuanze_questions=xuanze_questions,
                           tiankong_questions=tiankong_questions,
                           zhuguan_questions=zhuguan_questions)


# @app.route('/exam_list')
# def exam_list():
#     conn = get_db_connection()
#     cursor = conn.cursor(dictionary=True)
#
#     cursor.execute('SELECT * FROM papers')
#     papers = cursor.fetchall()
#
#     for exam in papers:
#         cursor.execute('''
#             SELECT q.id, q.question_text, q.option_a, q.option_b, q.option_c, q.option_d
#             FROM questions q
#             JOIN exam_questions eq ON q.id = eq.question_id
#             WHERE eq.exam_id = %s
#             ORDER BY eq.id ASC
#         ''', (exam['id'],))
#         exam['questions'] = cursor.fetchall()
#
#     cursor.close()
#     conn.close()
#
#     return render_template('exam_list.html', papers=papers)
#
#
# @app.route('/submit_answer/<int:question_id>', methods=['POST'])
# def submit_answer(question_id):
#     selected_answer = request.form['answer']
#
#     # 这里可以处理答案的存储或评估逻辑
#     # 比如存储用户选择的答案到数据库，或直接评估答案是否正确
#
#     return redirect(url_for('exam_list'))  # 提交后重定向回试卷列表页面

@app.route('/exam_list/<int:paper_id>')
def exam_list(paper_id):
    conn = get_db_connection()
    cursor = conn.cursor(dictionary=True)

    # 获取指定试卷的所有题目
    cursor.execute('SELECT * FROM examquestions WHERE paper_id = %s', (paper_id,))
    questions = cursor.fetchall()

    cursor.close()
    conn.close()

    return render_template('exam_list.html', questions=questions, exam_id=paper_id)

@app.route('/edit_exam_question/<int:question_id>', methods=['GET', 'POST'])
def edit_exam_question(question_id):
    conn = get_db_connection()
    cursor = conn.cursor(dictionary=True)

    cursor.execute('SELECT * FROM examquestions WHERE id = %s', (question_id,))
    question = cursor.fetchone()

    if request.method == 'POST':
        sql = '''
        UPDATE examquestions
        SET question_text = %s, option_a = %s, option_b = %s, option_c = %s, option_d = %s, correct_answer = %s
        WHERE id = %s
        '''
        cursor.execute(sql, (
            request.form['question_text'],
            request.form.get('option_a'),
            request.form.get('option_b'),
            request.form.get('option_c'),
            request.form.get('option_d'),
            request.form['correct_answer'],
            question_id
        ))

        conn.commit()
        cursor.close()
        conn.close()

        return redirect(url_for('exam_list', paper_id=question['paper_id']))

    cursor.close()
    conn.close()

    return render_template('edit_exam_question.html', question=question)

@app.route('/preview_exam/<int:paper_id>', methods=['GET'])
def preview_exam(paper_id):
    conn = get_db_connection()
    cursor = conn.cursor(dictionary=True)

    cursor.execute('SELECT * FROM papers WHERE id = %s', (paper_id,))
    exam = cursor.fetchone()

    cursor.execute('SELECT * FROM examquestions WHERE paper_id = %s', (paper_id,))
    questions = cursor.fetchall()

    cursor.close()
    conn.close()

    return render_template('preview_exam.html', exam=exam, questions=questions)

if __name__ == '__main__':
    app.run(debug=True)

